package com.jieshuibao.service;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.jieshuibao.common.config.Global;
import com.jieshuibao.common.res.BaseRes;
import com.jieshuibao.mapper.AnswerUserMapper;
import com.jieshuibao.mapper.CompanyMapper;
import com.jieshuibao.mapper.QuestionMapper;
import com.jieshuibao.mapper.QuestionUserMapper;
import com.jieshuibao.mapper.SecretlyMapper;
import com.jieshuibao.mapper.UserDealRecordMapper;
import com.jieshuibao.mapper.UserMapper;
import com.jieshuibao.model.db.Answer;
import com.jieshuibao.model.db.Company;
import com.jieshuibao.model.db.Integral;
import com.jieshuibao.model.db.Question;
import com.jieshuibao.model.db.QuestionExample;
import com.jieshuibao.model.db.QuestionExample.Criteria;
import com.jieshuibao.model.db.QuestionUserKey;
import com.jieshuibao.model.db.Secretly;
import com.jieshuibao.model.db.User;
import com.jieshuibao.model.db.UserDealRecord;
import com.jieshuibao.model.domain.Integrals;
import com.jieshuibao.util.JsonUtil;
import com.jieshuibao.util.MoneyRandom;
import com.jieshuibao.util.PayTypeUtil;
import com.jieshuibao.util.UUIDGenerator;
import com.jieshuibao.wx.util.PayCommonUtil;

@Service
public class QuestionService{
	
	private static final Logger logger = Logger.getLogger(QuestionService.class);
	
	@Resource
	private QuestionMapper questionMapper;
	
	@Resource
	private QuestionUserMapper questionUserMapper;
	
	@Resource
	private UserMapper userMapper;
	
	@Resource
	private SecretlyMapper secretlyMapper;
	
	@Resource
	private UserDealRecordMapper userDealRecordMapper; 
	
	@Resource
	private CompanyMapper companyMapper;
	
	@Resource
	private RedisService redisService;
	
	@Resource
	private IntegralService integralService;
	
	@Resource
	private AnswerUserMapper answerUserMapper;
	
	public void addQuestion(Question question) {
		questionMapper.insertSelective(question);
	}
	public void delQuestionByUuid(String uuid) {
		questionMapper.deleteByPrimaryKey(uuid);
	}
	
	public void updateQuestion(Question question) {
		questionMapper.updateByPrimaryKeySelective(question);
	}
	
	public Question getQuestionByUuid(String uuid) {
		return questionMapper.selectByPrimaryKey(uuid);
	}
	
	public List<Question> getPageQuestion(QuestionExample questionExample) {
		return questionMapper.selectPage(questionExample);
	}
	
	public int countQuestion(QuestionExample questionExample) {
		return questionMapper.countByExample(questionExample);
	}
	public void updateAfterTTK(QuestionUserKey record, User user, User answerUser, Secretly secretly, UserDealRecord userDealRecord, UserDealRecord userDealRecord1, UserDealRecord userDealRecord2, UserDealRecord userDealRecord4, UserDealRecord userDealRecord5) {
		if(record!=null){
			questionUserMapper.insertSelective(record);
			logger.info("TTK 用户问题中间表插入数据："+JsonUtil.toJson(record));
		}
		if(user!=null){
			userMapper.updateByPrimaryKeySelective(user);
			logger.info("TTK 提问题人得到钱："+JsonUtil.toJson(user));
		}
		if(answerUser!=null){
			userMapper.updateByPrimaryKeySelective(answerUser);
			logger.info("TTK回答问题人得钱："+JsonUtil.toJson(answerUser));
		}
		if(secretly!=null){
			secretlyMapper.updateByPrimaryKeySelective(secretly);
			logger.info("TTK业务表修改状态为成功："+JsonUtil.toJson(secretly));
		}
		if(userDealRecord!=null){
			userDealRecordMapper.insert(userDealRecord);
			logger.info("TTK偷看人支出流水："+JsonUtil.toJson(userDealRecord));
		}
		if(userDealRecord1!=null){
			userDealRecordMapper.insert(userDealRecord1);
			logger.info("TTK公司入账流水："+JsonUtil.toJson(userDealRecord1));
		}
		if(userDealRecord2!=null){
			userDealRecordMapper.insert(userDealRecord2);
			logger.info("TTK公司支出流水："+JsonUtil.toJson(userDealRecord2));
		}
		if(userDealRecord4!=null){
			userDealRecordMapper.insert(userDealRecord4);
			logger.info("TTK提问题人入账流水："+JsonUtil.toJson(userDealRecord4));
		}
		if(userDealRecord5!=null){
			userDealRecordMapper.insert(userDealRecord5);
			logger.info("TTK回答问题人入账流水："+JsonUtil.toJson(userDealRecord5));
		}
		
	}
	public void updateUserAndAddQuestion(User user,Question question){
		if(user!=null){
			userMapper.updateByPrimaryKeySelective(user);
		}
		if(question!=null){
			String payType = question.getPayType();
			
			questionMapper.insertSelective(question);
			String uuid1 = UUIDGenerator.getUUID();//用户
			String uuid2 = UUIDGenerator.getUUID();//解税宝
			UserDealRecord userDealRecord1=new UserDealRecord();
			UserDealRecord userDealRecord2=new UserDealRecord();
			userDealRecord1.setUuid(uuid1);
			userDealRecord2.setUuid(uuid2);
			userDealRecord1.setUserId(question.getPhoneNum());
			userDealRecord1.setAccountType(PayTypeUtil.ACCOUNTTYPE_PERSONAL);
			userDealRecord2.setUserId(PayTypeUtil.COMPANY_ACCPUNT);
			userDealRecord2.setAccountType(PayTypeUtil.ACCOUNTTYPE_BUSINESS);
			userDealRecord1.setBusinessNo(question.getUuid());
			userDealRecord2.setBusinessNo(question.getUuid());
			Date date = new Date();
			userDealRecord1.setCreateDate(date);
			userDealRecord2.setCreateDate(date);
			userDealRecord1.setSum((double)question.getMoney());
			userDealRecord2.setSum((double)question.getMoney());
			userDealRecord1.setGoodsType(PayTypeUtil.GOODSTYPE_REWARD);
			userDealRecord2.setGoodsType(PayTypeUtil.GOODSTYPE_REWARD);
			userDealRecord1.setTradeType(PayTypeUtil.TRDETYPE_EXPENDITURE);
			userDealRecord2.setTradeType(PayTypeUtil.TRDETYPE_INCOME);
			userDealRecord1.setPaySucTime(date);
			userDealRecord2.setPaySucTime(date);
			userDealRecord1.setPayType(payType);
			userDealRecord2.setPayType(payType);
			userDealRecord1.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
			userDealRecord2.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
			userDealRecordMapper.insertSelective(userDealRecord1);
			userDealRecordMapper.insertSelective(userDealRecord2);
		}
		
	}
	//发布悬赏 用企业会员卡支付
	public HashMap<String, String> updateCompanyAndQuestion(User user,double money,Question question) throws Exception{
		HashMap<String,String> hashMap = new HashMap<String, String>();
		
		if(user!=null&&question!=null){
			Integer companyRole = user.getCompanyRole();
			if(companyRole==0){
				hashMap.put("code", "3");
				hashMap.put("des", "你不是企业用户不能使用企业会员卡支付");
				return hashMap;//不能使用
			}else {
				String companyUuid = user.getCompanyUuid();
				Company company = companyMapper.selectByPrimaryKey(companyUuid);
				if(company==null){
					hashMap.put("code", "3");
					hashMap.put("des", "企业id错误");
					return hashMap;//不能使用
				}else {
					Double businessBalance = company.getBusinessBalance();
					if(businessBalance>=money){
						company.setBusinessBalance(businessBalance-money);
						question.setPayType(PayTypeUtil.PAYTYPE_COMPANYBALANCE);
						question.setPayStatus(PayCommonUtil.PAYSUCCESS_STATUS);
						String uuid1 = UUIDGenerator.getUUID();
						String uuid2 = UUIDGenerator.getUUID();
						UserDealRecord userDealRecord1=new UserDealRecord();
						UserDealRecord userDealRecord2=new UserDealRecord();
						userDealRecord1.setUuid(uuid1);//用户的支出（ 企业会员卡）
						userDealRecord2.setUuid(uuid2);//解税宝公司收入
						
						userDealRecord1.setAccountType(PayTypeUtil.ACCOUNTTYPE_PERSONAL);
						userDealRecord2.setAccountType(PayTypeUtil.ACCOUNTTYPE_BUSINESS);
						
						userDealRecord1.setUserId(companyUuid);
						userDealRecord2.setUserId(PayTypeUtil.COMPANY_ACCPUNT);
						
						userDealRecord1.setBusinessNo(question.getUuid());
						userDealRecord2.setBusinessNo(question.getUuid());
						Date date = new Date();
						userDealRecord1.setCreateDate(date);
						userDealRecord2.setCreateDate(date);
						userDealRecord1.setSum(money);
						userDealRecord2.setSum(money);
						userDealRecord1.setGoodsType(PayTypeUtil.GOODSTYPE_REWARD);
						userDealRecord2.setGoodsType(PayTypeUtil.GOODSTYPE_REWARD);
						userDealRecord1.setTradeType(PayTypeUtil.TRDETYPE_EXPENDITURE);
						userDealRecord2.setTradeType(PayTypeUtil.TRDETYPE_INCOME);
						userDealRecord1.setPaySucTime(date);
						userDealRecord2.setPaySucTime(date);
						userDealRecord1.setPayType(PayTypeUtil.PAYTYPE_COMPANYBALANCE);
						userDealRecord2.setPayType(PayTypeUtil.PAYTYPE_COMPANYBALANCE);
						userDealRecord1.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
						userDealRecord2.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
						userDealRecordMapper.insertSelective(userDealRecord1);
						userDealRecordMapper.insertSelective(userDealRecord2);
						questionMapper.insertSelective(question);
						companyMapper.updateByPrimaryKeySelective(company);
						hashMap.put("code", "1");
						hashMap.put("des", "发布悬赏成功");
						return hashMap;//不能使用
						
					}else {
						hashMap.put("code", "4");
						hashMap.put("des", "企业会员卡余额不足");
						return hashMap;//不能使用
					}
				}
			}
			
			
		}else {
			hashMap.put("code", "3");
			hashMap.put("des", "数据格式错误！！~");
			return hashMap;
		}
		
	}	
		
		
	/**
	 * 加赏
	 * @param user 微信支付可以不传
	 * @param phoneNumber 手机号
	 * @param money 加赏金额
	 * @param questionUuid 问题的uuid
	 * @param payType  支付方式
	 * @return
	 * @throws Exception
	 */
	public HashMap<String, String> updateUserAndQuestionAndOrCompany(User user,String phoneNumber,int money,String questionUuid,String payType) throws Exception{
		HashMap<String,String> hashMap = new HashMap<String, String>();
		if(questionUuid!=null){
			Date date = new Date();
			Calendar calendar = Calendar.getInstance();
			calendar.setTimeInMillis((date.getTime())
					+ ((long) 1) * 24 * 3600 * 1000);
			Question question2 = new Question();
			question2.setUuid(questionUuid);
			question2.setEndDate(calendar.getTime());
			question2.setAddMoney(money);
			question2.setRewardNum(1);
			question2.setAnswerNum(0);
			//流水
			String uuid1 = UUIDGenerator.getUUID();
			String uuid2 = UUIDGenerator.getUUID();
			UserDealRecord userDealRecord1=new UserDealRecord();
			UserDealRecord userDealRecord2=new UserDealRecord();
			userDealRecord1.setUuid(uuid1);//用户的支出（ 企业会员卡）
			userDealRecord2.setUuid(uuid2);//解税宝公司收入
			
			userDealRecord1.setAccountType(PayTypeUtil.ACCOUNTTYPE_PERSONAL);
			userDealRecord2.setAccountType(PayTypeUtil.ACCOUNTTYPE_BUSINESS);
			
			userDealRecord2.setUserId(PayTypeUtil.COMPANY_ACCPUNT);
			
			userDealRecord1.setBusinessNo(questionUuid);
			userDealRecord2.setBusinessNo(questionUuid);
			userDealRecord1.setCreateDate(date);
			userDealRecord2.setCreateDate(date);
			userDealRecord1.setSum((double)money);
			userDealRecord2.setSum((double)money);
			
			userDealRecord1.setGoodsType(PayTypeUtil.GOODSTYPE_ADDREWARD);
			userDealRecord2.setGoodsType(PayTypeUtil.GOODSTYPE_ADDREWARD);
			
			userDealRecord1.setTradeType(PayTypeUtil.TRDETYPE_EXPENDITURE);
			userDealRecord2.setTradeType(PayTypeUtil.TRDETYPE_INCOME);
			userDealRecord1.setPaySucTime(date);
			userDealRecord2.setPaySucTime(date);
			
			userDealRecord1.setPayType(PayTypeUtil.PAYTYPE_COMPANYBALANCE);//待定
			userDealRecord2.setPayType(PayTypeUtil.PAYTYPE_COMPANYBALANCE);
			
			userDealRecord1.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
			userDealRecord2.setStatus(PayCommonUtil.PAYSUCCESS_STATUS);
			
			User user2 = new User();
			if(payType.equals("balance")){
				
				Double balance = user.getBalance();
				if(money<=balance){
					user2.setPhoneNumber(phoneNumber);
					user2.setBalance(balance-money);
					question2.setAddType(PayTypeUtil.PAYTYPE_BALANCE);
					userDealRecord1.setPayType(PayTypeUtil.PAYTYPE_BALANCE);//待定
					userDealRecord2.setPayType(PayTypeUtil.PAYTYPE_BALANCE);
					userDealRecord1.setUserId(phoneNumber);// 待定
					userMapper.updateByPrimaryKeySelective(user2);
					questionMapper.updateByPrimaryKeySelective(question2);
					userDealRecordMapper.insertSelective(userDealRecord1);
					userDealRecordMapper.insertSelective(userDealRecord2);
					hashMap.put("code", "1");
					hashMap.put("des", "加赏成功");
					
				}else {
					//余额不足
					hashMap.put("code", "4");
					hashMap.put("des", "钱包余额不足");
					return hashMap;
					
				}
				
			}else if(payType.equals("personal")){
				Double vipBalance = user.getVipBalance();
				if(vipBalance>=money){
					user2.setPhoneNumber(phoneNumber);
					user2.setBalance(vipBalance-money);
					question2.setAddType(PayTypeUtil.PAYTYPE_VIPBALANCE);
					userDealRecord1.setPayType(PayTypeUtil.PAYTYPE_VIPBALANCE);//待定
					userDealRecord2.setPayType(PayTypeUtil.PAYTYPE_VIPBALANCE);
					userDealRecord1.setUserId(phoneNumber);// 待定
					userMapper.updateByPrimaryKeySelective(user2);
					questionMapper.updateByPrimaryKeySelective(question2);
					userDealRecordMapper.insertSelective(userDealRecord1);
					userDealRecordMapper.insertSelective(userDealRecord2);
					hashMap.put("code", "1");
					hashMap.put("des", "加赏成功");
					
				}else {
					//余额不足
					hashMap.put("code", "4");
					hashMap.put("des", "个人会员卡不足");
					return hashMap;
				}
				
				
			}else if(payType.equals("business")){//business
				Integer companyRole = user.getCompanyRole();
				if(companyRole!=0){
					String companyUuid = user.getCompanyUuid();
					Company company = companyMapper.selectByPrimaryKey(companyUuid);
					if(company!=null){
						Double businessBalance = company.getBusinessBalance();
						if(businessBalance>=money){
							company.setBusinessBalance(businessBalance-money);
							question2.setAddType(PayTypeUtil.PAYTYPE_COMPANYBALANCE);
							userDealRecord1.setPayType(PayTypeUtil.PAYTYPE_COMPANYBALANCE);//待定
							userDealRecord2.setPayType(PayTypeUtil.PAYTYPE_COMPANYBALANCE);
							userDealRecord1.setUserId(companyUuid);// 待定
							companyMapper.updateByPrimaryKeySelective(company);
							questionMapper.updateByPrimaryKeySelective(question2);
							userDealRecordMapper.insertSelective(userDealRecord1);
							userDealRecordMapper.insertSelective(userDealRecord2);
							hashMap.put("code", "1");
							hashMap.put("des", "加赏成功");
						
						}else {
							//余额不足
							hashMap.put("code", "4");
							hashMap.put("des", "企业会员卡不足");
							return hashMap;
						}
					}else {
						//数据格式错误
						hashMap.put("code", "3");
						hashMap.put("des", "没有找到公司");
						return hashMap;
					}
				}else {
					//不能使用
					hashMap.put("code", "3");
					hashMap.put("des", "您不能使用企业会员卡支付");
					return hashMap;
				}
				
			}else if(payType.equals("weixin")){
				question2.setAddType(PayTypeUtil.PAYTYPE_WEIXIN);
				userDealRecord1.setPayType(PayTypeUtil.PAYTYPE_WEIXIN);//待定
				userDealRecord2.setPayType(PayTypeUtil.PAYTYPE_WEIXIN);
				userDealRecord1.setUserId(phoneNumber);// 待定
				questionMapper.updateByPrimaryKeySelective(question2);
				userDealRecordMapper.insertSelective(userDealRecord1);
				userDealRecordMapper.insertSelective(userDealRecord2);
				hashMap.put("code", "1");
				hashMap.put("des", "加赏成功");
			
			}else {
				hashMap.put("code", "3");
				hashMap.put("des", "支付方式错误");
				return hashMap;
			}
			redisService.delete(questionUuid+"_num");
			return hashMap;
		}else {
			hashMap.put("code", "3");
			hashMap.put("des", "数据格式错误！！~");
			return hashMap;
		}
		
	}
	public void updateAfterXS(Question question, UserDealRecord userDealRecord, UserDealRecord userDealRecord1) {
		questionMapper.updateByPrimaryKeySelective(question);
		logger.info("XS修改悬赏问题状态："+JsonUtil.toJson(question));
		userDealRecordMapper.insertSelective(userDealRecord);
		logger.info("XS悬赏人支出流水："+JsonUtil.toJson(userDealRecord));
		userDealRecordMapper.insertSelective(userDealRecord1);
		logger.info("XS公司入账流水："+JsonUtil.toJson(userDealRecord1));
	}
	
	/**
	 * 用户级别 提问次数限制
	 * @return
	 */
	public BaseRes<String> IntegralUserQuestion(String userId){
		Integrals integrals = integralService.getIntegralsByUuid(userId);
		BaseRes<String> res = new BaseRes<String>();
		
		if (integrals!=null) {
			QuestionExample questionExample = new QuestionExample();
			Criteria createCriteria = questionExample.createCriteria();
			createCriteria.andPhoneNumEqualTo(userId);
			createCriteria.andPayStatusEqualTo(PayCommonUtil.PAYSUCCESS_STATUS);
			Date beforeDateTime = MoneyRandom.getBeforeDateTime();
			createCriteria.andDateGreaterThan(beforeDateTime);
			int countByExample = questionMapper.countByExample(questionExample);
			int integralSum = integrals.getIntegralSum();
			
			if (integralSum<6) {
				//普通会员不能提问
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes("普通会员不能提问");
				return res;
				
			}else if (integralSum>=6&&integralSum<20) {
				if (countByExample>=2) {
					//铜牌会员只能问两次
					res.setCode(BaseRes.ERRORPARAM_CODE);
					res.setDes("铜牌会员只能问两次");
					return res;
				}
			}else if (integralSum>=20&&integralSum<50) {
				if (countByExample>=5) {
					//银牌会员只能问两5次
					res.setCode(BaseRes.ERRORPARAM_CODE);
					res.setDes("银牌会员只能问两5次");
					return res;
				}
			}else if (integralSum>=50&&integralSum<100) {
				if (countByExample>=10) {
					//金牌会员只能问两10次
					res.setCode(BaseRes.ERRORPARAM_CODE);
					res.setDes("金牌会员只能问两10次");
					return res;
				}
			}
			res.setCode(BaseRes.SUCCESS_CODE);
			res.setDes(BaseRes.SUCCESS_DES);
			return res;
		}else {
			Integral integral = new Integral();
			integral.setUuid(userId);
			integral.setRegist(1);
			integralService.addIntegral(integral);
			//普通会员不能提问
			res.setCode(BaseRes.ERRORPARAM_CODE);
			res.setDes("普通会员不能提问");
			return res;
		}
	}
	
	//是否还有未采纳答案的问题
	
	public boolean isAdopQuestion(String userId){
		QuestionExample questionExample = new QuestionExample();
		Criteria createCriteria = questionExample.createCriteria();
		createCriteria.andPhoneNumEqualTo(userId);
		createCriteria.andAnswerNumEqualTo(2);
		createCriteria.andStatusEqualTo(1);
		createCriteria.andDelFlagEqualTo(Global.SHOW);
		
		List<Question> selectByExample = questionMapper.selectByExample(questionExample);
		for (Question question : selectByExample) {
			String uuid = question.getUuid();
			List<Answer> answers = answerUserMapper.selectAnswerIsAdop(uuid);
			//List<Answer> answers = answerUserMapper.selectAnswerApproveNum(uuid, 1);
			if (answers!=null&&answers.size()>0) {
				return true;
			}
		}
		return false;
	}
	
}
